package com.gewu.bluetoothflow.ui

import android.content.Context
import android.content.IntentFilter
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eciot.ble_demo_kotlin.ECBLE
import com.gewu.bluetoothflow.MyApp.Companion.ACTION_SEND_DATA
import com.gewu.bluetoothflow.R
import com.gewu.bluetoothflow.adapter.FlowDataAdatper

import com.gewu.bluetoothflow.bean.FlowCount
import com.gewu.bluetoothflow.bean.FlowData
import com.gewu.bluetoothflow.databinding.ActivityFlowdataBinding
import com.gewu.bluetoothflow.service.DataRefreshReceiver
import com.gewu.bluetoothflow.tools.CreateExcelFile
import com.google.gson.Gson
import java.io.File
import java.io.IOException
import java.util.*



class FlowDataActivity :BaseActivity(),DataRefreshReceiver.Messages {
    val TAG: String = "FlowDataActivity"

    private lateinit var mbinding: ActivityFlowdataBinding;
    private lateinit var condition:MutableList<String> ;

     var selectCondition = 0;
     var dataReceiver: DataRefreshReceiver? = null;
     var sendStatus = -1
    lateinit var dataAdapter:FlowDataAdatper
    var mdata :MutableList<FlowCount> = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mbinding = ActivityFlowdataBinding.inflate(layoutInflater)
        setContentView(mbinding.root)

        condition =  mutableListOf<String>(resources.getString(R.string.get_hour_data),
            resources.getString(R.string.get_day_data), resources.getString(R.string.get_month_data))

        val adapter = ArrayAdapter (this,R.layout.spinner_item,condition)
        mbinding.searchTime.adapter = adapter
        dataReceiver = DataRefreshReceiver(this)
        val initentFilter = IntentFilter()
        initentFilter.addAction(ACTION_SEND_DATA)
        registerReceiver(dataReceiver,initentFilter, Context.RECEIVER_NOT_EXPORTED)


        mbinding.tvBack.setOnClickListener { finish() }
        mbinding.searchTime.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                Log.d(TAG,"====> i : $p2  p3:$p3  condition:${condition.get(p2)}" )
                selectCondition = p2
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }
        }

        dataAdapter = FlowDataAdatper(this)
        val layoutManager= LinearLayoutManager(this)
        mbinding.ryData.adapter = dataAdapter
        mbinding.ryData.itemAnimator = null
        layoutManager.orientation = RecyclerView.VERTICAL
        mbinding.ryData.layoutManager = layoutManager
        mbinding.ryData.addOnScrollListener(verticalRvScrollListener)

        mbinding.queryData.setOnClickListener {
            var  command = "{\"hoursData\":\"get\"}"
            when(selectCondition){
                0->{ //"获取小时数据"
                     command = "{\"hoursData\":\"get\"}"
                }
                1->{ //"获取天数据"
                      command = "{\"daysData\":\"get\"}"
                }
                2->{// "获取月数据"
                      command = "{\"monthsData\":\"get\"}"
                }
            }
            sendStatus = 1
            val state = ECBLE.writeBLECharacteristicValue(command, false)
            if (state){
                showToast(resources.getString(R.string.query_success))
            }else{
                showToast(resources.getString(R.string.query_fail))
            }

            Timer().schedule(
               object :TimerTask(){
                   override fun run() {
                       if (sendStatus == 2) return
                      val status = false // if (sendStatus == 2) true else
                       var  command = "{\"hoursDataSta\":\"$status\"}"
                       when(selectCondition){
                           0->{ //"获取小时数据"
                               command =  "{\"hoursDataSta\":\"$status\"}"
                           }
                           1->{ //"获取天数据"
                               command = "{\"daysDataSta\":\"$status\"}"
                           }
                           2->{// "获取月数据"
                               command = "{\"monthsDataSta\":\"$status\"}"
                           }
                       }
                       Log.d(TAG,"timer: -- >  $sendStatus  $command")
                       val state = ECBLE.writeBLECharacteristicValue(command, false)
                   }
               },20000
            )
        }
        //导出文件
        mbinding.btExport.setOnClickListener {
           if (mdata.size > 0){
              val state = CreateExcelFile.startCreateFile(getFile(),mdata)
               if (state){
                   showToast(getString(R.string.goto_sysfile_management_to_for_excel_folder))
               }else{
                   showToast(getString(R.string.export_fail))
               }
           }else{
               showToast(getString(R.string.not_found_search_data))
           }
        }
    }

    fun getFile():String{
        val path = Environment.getExternalStorageDirectory().absolutePath
        Log.d("ExcelActivity", "path:$path")
        val directory =
            "$path/excel"
       val times = timeFormat.format(System.currentTimeMillis())
        val fileName = "/${times}_客流.xlsx"
        val abFilePath = "$directory$fileName"
        Log.d(TAG, "directory:$directory")
        Log.d(TAG, "abFilePath:$abFilePath")


        val fileDirectory = File(directory)
        val file = File(abFilePath)
        try {
            if (!fileDirectory.exists()) {
                fileDirectory.mkdirs()
                Log.e(TAG, "路径不存在创建路径")
            }
            file.createNewFile();
        } catch (e: IOException) {
            Log.e(TAG, "createNewFile e:$e")
            e.printStackTrace()
            return ""
        }
        Log.d(TAG, "文件创建成功:${file.absolutePath} ${file.exists()}")
        if (!file.exists()) {
            return ""
        }
       return abFilePath
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(dataReceiver)
    }

    var flowData = mutableMapOf<String,MutableList<FlowCount>>()
    override fun getMsg(str: String) {
        sendStatus = 2
        var  command = "{\"hoursDataSta\":\"true\"}"
        when(selectCondition){
            0->{ //"获取小时数据"
                command =  "{\"hoursDataSta\":\"true\"}"
            }
            1->{ //"获取天数据"
                command = "{\"daysDataSta\":\"true\"}"
            }
            2->{// "获取月数据"
                command = "{\"monthsDataSta\":\"true\"}"
            }
        }
        Log.d(TAG,"timer: -- >  $sendStatus  $command  " + Thread.currentThread().name)
        val state = ECBLE.writeBLECharacteristicValue(command, false)
       val currentData = Gson().fromJson(str, FlowData::class.java)
       if (currentData == null) return

      // var data = flowData.get(currentData.type)
        mdata.addAll(currentData.data!!)
        if (currentData.state.equals("1")){
           loadData()
        }
    }
    val prePageCount = 50
    private var verticalRvVisibleItemCount = 0
    private val verticalRvScrollListener = object : RecyclerView.OnScrollListener() {
        private var scrollToBottom = false
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            (recyclerView.layoutManager as? LinearLayoutManager)?.let { linearLayoutManager ->
                // 判断是拖动或者惯性滑动
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    if (verticalRvVisibleItemCount == 0) {
                        // 获取列表可视Item的数量
                        verticalRvVisibleItemCount = linearLayoutManager.findLastVisibleItemPosition() - linearLayoutManager.findFirstVisibleItemPosition()
                    }
                    // 判断是向着列表尾部滚动，并且临界点已经显示，可以加载更多数据。
                    if (scrollToBottom && linearLayoutManager.findViewByPosition(linearLayoutManager.itemCount - 1 - verticalRvVisibleItemCount) != null) {
                        loadData()
                    }
                }
            }
        }
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            // 判断列表是向列表尾部滚动
            scrollToBottom = dy > 0
        }
    }
    fun loadData() {
        val init = mbinding.ryData.adapter!!.itemCount == 0
        val start = mbinding.ryData.adapter!!.itemCount
        val end = mbinding.ryData.adapter!!.itemCount + prePageCount
        val testData = ArrayList<FlowCount>()
        if (mdata.size > end){
            testData.addAll(mdata.subList(start,end))
        }
        if (mdata.size > start && mdata.size <= end){
            testData.addAll(mdata.subList(start,mdata.size))
        }
        if (init) {
            dataAdapter.setNewData(testData)
        } else {
            dataAdapter.addData(testData)
        }
    }

}